mkdir ./.vscode

# ANSI color
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
GRAY='\033[1;30m'
NC='\033[0m' # No Color

confirm_action() {
    while : ; do
        echo -e "${BLUE}$1${NC} ${YELLOW} [Y/N] ${NC}"
        read -r response
        
        case $response in
            [Yy]|"" ) return 0 ;;    # Y/y或回车确认
            [Nn]   ) echo -e "${RED}操作已取消${NC}"; exit 1 ;;
            *      ) echo -e "${RED}无效输入，请按 Y 或 N${NC}" ;;
        esac
    done
}
confirm_action "♿准备好享受轮椅了吗♿"

# build.sh
cat > ./.vscode/build.sh<< 'EOF'
#run.sh

# ANSI color
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
GRAY='\033[1;30m'
NC='\033[0m' # No Color

# Check and remove build
BUILD_DIR="build"
if [ "$(basename "$PWD")" = "build" ]; then
    echo -e "${RED}ERROR:Do not run this bash in build directory${NC}"
    exit 1
fi

if [ -d "$BUILD_DIR" ]; then
    echo -e "${YELLOW}WARNING: Removing existing build directory...${NC}"
    rm -rf "$BUILD_DIR"
    if [ $? -ne 0 ]; then
        echo -e "${RED}ERROR: Failed to remove build directory${NC}"
        exit 1
    fi
    echo -e "${GREEN}Build directory cleaned${NC}"
fi

# Check dependencies and Info version 
check_dependency() {
    if ! command -v "$1" &> /dev/null; then
        echo -e "${RED}ERROR: Could not find $1,please check you environment variable or need other help${NC}"
        exit 1
    else
        echo -e "${GREEN}checking the version of $1${NC}"
        $1 --version | head -n 1  
    fi
}

echo -e "${BLUE}Check your environment...${NC}"
check_dependency clangd
check_dependency arm-none-eabi-gcc
check_dependency cmake
check_dependency ninja
check_dependency openocd

echo -e "${GREEN} 🌠Check environment has done ${NC}"

# Set 
TOOLCHAIN_FILE="./cmake/gcc-arm-none-eabi.cmake"
BUILD_DIR="./build"
JOBS=8

# Check arm-gcc toolchain file
if [ ! -f "$TOOLCHAIN_FILE" ]; then
    echo -e "${RED}ERROR:Do not find toolchain file, please check if you have cmake/gcc-arm-none-eabi.cmake $TOOLCHAIN_FILE${NC}"
    exit 1
fi

#Configure and build
echo -e "${BLUE} 🌟Building...🌟 ${NC}"
cmake -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN_FILE" -GNinja -B "$BUILD_DIR"
if [ $? -ne 0 ]; then
    echo -e "${RED}Error:CMake configure failed ${NC}"
    exit 1
fi

# Reset clangd language server
restart_clangd() {
    ## 检查 clangd 是否安装
    if ! command -v clangd >/dev/null 2>&1; then
        echo -e "${GRAY}[Note] clangd not installed${NC}"
        return 1
    fi
    
    ## 检查是否已有 clangd 进程在运行
    if pgrep -x clangd >/dev/null; then
        echo -e "${RED}✗ clangd is already running${NC}"
        return 1
    fi
    
    ## 启动 clangd 并捕获输出
    if clangd >/dev/null 2>&1 & then
        echo -e "${GREEN}✓ clangd started (PID: $!)${NC}"
        return 0
    else
        echo -e "${RED}✗ Failed to start clangd${NC}"
        return 1
    fi
}
restart_clangd

# Compile
echo -e "${BLUE} ⚡Compiling...⚡ ${NC}"
cd "$BUILD_DIR" || exit 1
ninja -j "$JOBS"
if [ $? -ne 0 ]; then
    echo -e "${RED}ERROR:Compile failed${NC}"
    exit 1
fi

echo ""

echo -e "${GRAY}Belongs to Laboratory 1024, RoboMaster Team Damocles of CCUT${NC}"

EOF

echo -e "${GREEN}🛠️The build.sh has been generated🛠️${NC}"
chmod +x ./.vscode/build.sh

# doownload.sh
cat > ./.vscode/download.sh << 'EOF'
# 配置区（根据实际情况修改）

## 下载器配置
INTERFACE_CFG="/usr/share/openocd/scripts/interface/stlink.cfg"
## 目标芯片配置  
TARGET_CFG="/usr/share/openocd/scripts/target/stm32f1x-2.cfg"  
# 要烧录的固件路径
ELF_FILE="./build/test.elf" 

# ANSI color
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
GRAY='\033[1;30m'
NC='\033[0m' # No Color



OPENOCD_PATH=$(command -v openocd)

check_file() {
    if [ ! -f "$1" ]; then
        echo "Error: missing - $1"
        exit 1
    fi
}

check_file "$ELF_FILE"
check_file "$INTERFACE_CFG"
check_file "$TARGET_CFG"

# Check OpenOCD
echo -e "${BLUE}=== 开始连接检查 ===${NC}"
TMP_LOG=$(mktemp)

"$OPENOCD_PATH" -f "$INTERFACE_CFG" \
                -f "$TARGET_CFG" \
                -c "program $ELF_FILE verify reset exit"

"$OPENOCD_PATH" -f "$INTERFACE_CFG" \
               -f "$TARGET_CFG" \
               -c "program $ELF_FILE verify reset" \
               -c "shutdown" > "$TMP_LOG" 2>&1

# Error
if grep -q "OpenOCD init failed" "$TMP_LOG" || grep -q "Error:" "$TMP_LOG"; then
    echo -e "${RED}🤡烧录失败😭 错误分析：${NC}"
    echo "-----------------------------------------------"
    
    #芯片ID不适配
    if grep -q "UNEXPECTED idcode" "$TMP_LOG"; then
        echo -e "${RED}芯片ID🈲不适配${NC}"
        echo "检测到的ID: $(grep -oE "UNEXPECTED idcode: 0x[0-9A-F]+" "$TMP_LOG")"
        echo "预期ID: $(grep -oE "expected [0-9]+ of [0-9]+: 0x[0-9A-F]+" "$TMP_LOG")"
    fi

    # 芯片未连接
    if grep -q "open failed" "$TMP_LOG";then
        echo -e "${YELLOW}调试器无法与目标芯片建立连接${NC}"
        echo "请检查硬件接线,openocd配置,Link驱动"
    fi

    # 其他未知错误

fi

# Succeed
if grep -q "Programming Finished" "$TMP_LOG" || grep -q "Verified OK" "$TMP_LOG"; then
    echo -e "${BLUE}🥳烧录成功😋${NC}"
    echo "-----------------------------------------------"

fi
rm "$TMP_LOG"

echo ""
echo -e "${GRAY}Belongs to Laboratory 1024, RoboMaster Team Damocles of CCUT${NC}"

EOF

echo -e "${GREEN}🖲️The download.sh has been generated🖲️${NC}"
chmod +x ./.vscode/download.sh

# launch.json
cat > ./.vscode/launch.json << 'EOF'
{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息，请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Cortex Debug",
            "cwd": "${workspaceFolder}",
            "executable": "./build/test.elf",
            "request": "launch",
            "type": "cortex-debug",
            "runToEntryPoint": "main",
            "servertype": "openocd",
            "showDevDebugOutput": "raw",
            "configFiles": [
               "/usr/share/openocd/scripts/interface/stlink.cfg",
               "/usr/share/openocd/scripts/target/stm32f1x-2.cfg"
            ]
        }
    ]
}

EOF

echo -e "${GREEN}🚀The launch.json has been generated🚀${NC}"

# setting.json
cat > ./.vscode/settings.json << 'EOF'
{
  "clangd.arguments": [
  "--function-arg-placeholders=false",
  "--header-insertion=never"
  ],

  "files.associations": 
   {
     "*.txt":"cmake"
   },

  "VsCodeTaskButtons.tasks": [
    {
      "label": "🔧Build and Compile",
      "task": "build",
      "alignment": "left",
      "color": "default",
    },
    {
      "label": "🖲️Download",
      "task": "download",
      "alignment": "left",
      "color": "default",
    }
  ]
}

EOF

echo -e "${GREEN}⚙️The setting.json has been generated⚙️${NC}"

# tasks.json
cat > ./.vscode/tasks.json << 'EOF'
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build",
      "type": "shell",
      "command": "./.vscode/build.sh",
      "windows": {
        "command": "bash",
        "args": ["-c", "./.vscode/build.sh"]
      },
      "group": "build",
      "presentation": {
        "reveal": "always",
        "panel": "dedicated",
        "clear": true
      }
    },

    {
      "label": "download",
      "type": "shell",
      "command": "./.vscode/download.sh",
      "windows": {
        "command": "bash",
        "args": ["-c", "./.vscode/download.sh"]
      },
      "group": "build",
      "presentation": {
        "reveal": "always",
        "panel": "dedicated",
        "clear": true
      }

    }
  ]
}

EOF

echo -e "${GREEN}🏆The tasks.json has been generated🏆${NC}"
echo ""
echo -e "${RED}◣◥DRANGR◣◥DRANGR◣◥DRANGR◣◥DRANGR◣◥${NC}"

rm -- "$0"  

sleep 0.5
echo ""
echo "cherno.sh version 1.2 20250731"
echo -e "${GRAY}Belongs to Laboratory 1024, RoboMaster Team Damocles of CCUT${NC}"
